package com.kyzh.core.download.down

import android.app.*
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import android.os.IBinder
import android.text.TextUtils
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.blankj.utilcode.util.NotificationUtils
import com.blankj.utilcode.util.Utils
import com.gushenge.core.beans.DownTaskBean
import com.gushenge.core.dao.MMKVConsts
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.MyApplication
import com.kyzh.core.R
import com.kyzh.core.pager.gamedetail.GameDetailActivity1
import com.kyzh.core.pager.home.MainActivity
import com.kyzh.core.utils.appInstall
import com.liulishuo.okdownload.StatusUtil
import org.jetbrains.anko.collections.forEachByIndex
import org.litepal.LitePal
import org.litepal.extension.findAll
import java.util.*

class DownService : Service() {
    private  var game : DownTaskBean? = null
    override fun onBind(intent: Intent?): IBinder? {
        return null
    }
    //https://mp.weixin.qq.com/s/ALY3BxRO1fb_F4Ol5t7Uig  通知可参考这个   后续修改
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val game1= intent?.getSerializableExtra("game")
        if(game1 is DownTaskBean){
            game = game1
        }
        createNotificationChannel()
        return super.onStartCommand(intent, flags, startId)
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun createNotificationChannel() {
        if(game!=null){
            createNotificationForProgress()
            var task = DownTask.map[game?.url]

            if(task!= null){
                task.tag = game?.url
                when( StatusUtil.getStatus(task)){
                    //处于下载完成  再次点击安装
                    StatusUtil.Status.COMPLETED ->{
                        game?.state = 3
                        game?.updateAll("url = ?", game?.url)
                        DownTask.postValue(game!!)
                        MyApplication.instance.appInstall(task)
                        stopSelf()

                    }
                    //处于下载  再次点击取消
                    StatusUtil.Status.RUNNING ->{
                        game?.state = 0
                        game?.updateAll("url = ?", game?.url)
                        DownTask.postValue(game!!)

                        task.cancel()
                    }
                    //处于闲置 再次点击开始下载
                    StatusUtil.Status.IDLE -> {
                        game?.state = 1
                        DownTask.postValue(game!!)
                        DownTask.downEnqueue(task, game!!)

                    }
                    //处于排队中  再次点击取消
                    StatusUtil.Status.PENDING->{
                        game!!.state = 0
                        game!!.updateAll("url = ?", game?.url)
                        DownTask.postValue(game!!)
                        task.cancel()

                    }
                    //处于未知状态  点击也让再次下载
                    else ->{

                        DownTask.downEnqueue(task, game!!)
                    }
                }
            }else{
                var i = 0
                task = DownTask.createDownloadTask(game!!)
                DownTask.map[game!!.url] = task
                DownTask.downEnqueue(task, game!!)
            }

        }

        updateNotificationForProgress()
    }
    private lateinit var mBuilder :NotificationCompat.Builder
    private var mManager:NotificationManager? = null
    private fun createNotificationForProgress() {
        game?.apply {
            val nid = if (TextUtils.equals(game!!.gid,"0")){
                "1"
            }else{
                game!!.gid
            }
//           val mFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
//                PendingIntent.FLAG_IMMUTABLE
//            } else {
//                PendingIntent.FLAG_UPDATE_CURRENT
//            }
            val mFlag = PendingIntent.FLAG_UPDATE_CURRENT

            val intentStop = Intent(this@DownService,MainActivity::class.java)
            val pendingIntentStop = PendingIntent.getActivity(this@DownService, 0, intentStop, mFlag)
            mManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel(nid, game!!.name, NotificationManager.IMPORTANCE_DEFAULT)
                mManager?.createNotificationChannel(channel)
            }
            mBuilder = NotificationCompat.Builder(this@DownService, nid).apply {
                setContentTitle("运行中")
                setSmallIcon(R.drawable.logo_new)
                setContentIntent(pendingIntentStop)

                setSound(null)
                setOnlyAlertOnce(true)
            }
            startForeground(Random().nextInt(10000), mBuilder!!.build() )
//            mManager?.notify(nid.toInt(), mBuilder!!.build())

        }


    }
    private fun updateNotificationForProgress() {
        LiveEventBus.get<Map<String,DownTaskBean>>("GAMETASK").observeForever{
            val all = LitePal.findAll<DownTaskBean>()
            all.forEachIndexed { index, downTaskBean ->
                val nid = if (TextUtils.equals(downTaskBean.gid,"0")){
                    "1"
                }else{
                    game!!.gid
                }
                if (::mBuilder.isInitialized) {
                    val mFlag = PendingIntent.FLAG_UPDATE_CURRENT
                    val intentStop = Intent(this@DownService,GameDetailActivity1::class.java)
                    intentStop.putExtra("gid",game!!.gid)
                    val pendingIntentStop = PendingIntent.getActivity(this@DownService, 0, intentStop, mFlag)
                    mBuilder.apply {
                        Log.e("TAG", "updateNotificationForProgress: "+game!!.name )
                        setContentTitle(game!!.name)
                        if(game!!.process.toInt()==100){
                            setContentText("下载完成")
                        }else{
                            setContentText("下载中：${game!!.process.toInt()}%")
                        }
                        setContentIntent(pendingIntentStop)
                        setSmallIcon(R.drawable.logo_new)
                        setProgress(100, game!!.process.toInt(), false)
                        setSound(null)
                        setOnlyAlertOnce(true)
                    }
                    mManager?.notify(nid.toInt(), mBuilder.build())
                } else {
                }
            }

        }

    }

    override fun onDestroy() {
        stopForeground(true)
        LiveEventBus.get<Map<String,DownTaskBean>>("GAMETASK").removeObserver {

        }
        Log.e("TAG", "onDestroy")
        super.onDestroy()
    }
}